import { IFeidaoAiBrowserComponent } from '@feidao/web/interfaces';
import { post } from '@feidao/web/request';
import { file_url, spaceid } from './config';

export default async function upload(fd: IFeidaoAiBrowserComponent, id: string, node: HTMLInputElement) {
	return (await up(node));
}

interface IFileDoc {
	_id: string;
	length: number;
	chunkSize: number;
	uploadDate: Date;
	md5: string;
	filename: string;
	contentType?: string;
	aliases?: string[];
	metadata?: {
		originialFileName?: string;
		productid?: string;
	};
	isDeleted?: boolean;
}

function up(node: HTMLInputElement) {
	return Promise.all<IFileDoc>(Array.from(node.files).map((file) => {
		const file_name = file.name;
		const r = new FileReader();
		r.readAsDataURL(file);
		return new Promise((resolve, reject) => {
			r.onload = async (e) => {
				const file_string = (e.target as any).result as string;
				const ret = await post(`${file_url}upload?productid=${spaceid}`, JSON.stringify({
					file_name,
					file_string
				}));
				resolve(JSON.parse(ret.responseText)[0]);
			};
			r.onerror = async (e) => {
				reject('fail');
			};
		});
	}));
}
